package com.sky.controller.user;

import com.alibaba.druid.support.json.JSONUtils;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * @aothor LentDent1
 * @vision 1.0
 */
@RestController
@RequestMapping("/user/user")
@Slf4j
@Api(tags = "用户层的相关接口")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 实现用户登录功能
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("实现用户登录功能")
    public Result<UserLoginVO> login (@RequestBody UserLoginDTO userLoginDTO) {
        // 传入UserLoginDTO 返回一个User对象
        User user = userService.wxLogin(userLoginDTO); // 后续步骤实现

        // 为user对象创建一个jwt令牌
        HashMap<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(),
                claims);

        // 将id，openid，token封装到new 的 UserLoginVo中
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();

        // 将对象返回
        return Result.success(userLoginVO);
    }
}
